package com.edais.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.edais.domain.InterfaceWhite;
import com.edais.domain.User;
import com.edais.service.SystemSettingService;
import com.edais.service.UserCheckService;
import com.edais.service.UserService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DES3Util;
import com.edais.util.StringUtil;

/**
 * 用户异常监测拦截
 * 
 * @author chen
 * 
 */
public class UserCheckInterceptor implements HandlerInterceptor {
	/** 日志 **/
	private static final Logger logger = Logger
			.getLogger(UserCheckInterceptor.class);

	@Autowired
	private UserService userService;

	@Autowired
	private UserCheckService userCheckService;

	@Autowired
	private SystemSettingService systemSettingService;

//	 @Autowired
//	 private ErrorMessageService errorMessageService;

	/**
	 * 在DispatcherServlet完全处理完请求后被调用
	 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion() 【用户异常监测】
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handle, Exception exception) {

	}

	/**
	 * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {

	}

	/**
	 * 在业务处理器处理请求之前被调用 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
	 * 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链,
	 * 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion() 【用户异常监测】
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse res, Object handler) {
		try {
			// 拦截开关
			String userCheckSwitch = systemSettingService
					.getSystemSettingValueByName("user_check_switch");
			logger.info("用户异常监测开关状态：" + userCheckSwitch);
			if ("Y".equalsIgnoreCase(userCheckSwitch)) {
				String userCheckWay = systemSettingService.getSystemSettingValueByName("user_check_way");
				if("1".equals(userCheckWay)){//全部拦截
					return check(request, res);
				}
				
				Map<String, String> validateMap = new HashMap<String, String>();
				validateMap.put("type", "1");// 0表示token拦截,1表示账户监测拦截
				validateMap.put("way", userCheckWay);// 拦截方案，1-全部拦截，2-部分拦截
				// 接口白名单
				List<InterfaceWhite> interfaceWhiteList = userCheckService
						.getAllInterfaceWhite(validateMap);
				if (null != interfaceWhiteList
						&& interfaceWhiteList.size() > 0) {
					logger.info("账户监测功能限制条数:" + interfaceWhiteList.size());
					String url = request.getRequestURI();
					logger.info("请求url：" + url);
					for (int j = 0; j < interfaceWhiteList.size(); j++) {
						if (url.split("/")[2].equals(interfaceWhiteList
								.get(j).getInterfaceName())
								&& url.split("/")[3]
										.equals(interfaceWhiteList.get(j)
												.getMethodName())) {
							return check(request, res);
						}
					}
				}
			}
			return true;
		} catch (Exception e) {
			logger.error("请求接口的拦截异常：", e);
			return true;
		}
	}

	private boolean check(HttpServletRequest request, HttpServletResponse res)
			throws Exception, IllegalAccessException {
		String result;
		Long userId = getUserId(request);
		if (null == userId) {
			return true;
		}
		// 判断用户是否异常
		if (userCheckService.isExistExceptionUser(userId)) {
			logger.info("监测到用户异常，userId:" + userId);
			Map errorMap = new HashMap<String, Object>();
			errorMap.put("errorFlag", "1");
			result = CommonUtil.setResultStringCn(
					errorMap,
					Consts.ERROR_CODE, "", "当前功能暂停使用，请联系客服。");
			CommonUtil.responseJson(result, res);
			return false;
		}
		return true;
	}

	private Long getUserId(HttpServletRequest request) throws Exception {
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id
		String mobile = paramsMap.get("mobile"); // 手机号
		String phoneNum = paramsMap.get("phoneNum"); // 手机号
		if (StringUtil.isNotEmpty(userId)) {
			return Long.valueOf(userId);
		}
		if (StringUtil.isNotEmpty(mobile)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mobile", mobile);
			User user = userService.getUserByParm(map);
			return Long.valueOf(user.getId());
		}
		if (StringUtil.isNotEmpty(phoneNum)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mobile", phoneNum);
			User user = userService.getUserByParm(map);
			return Long.valueOf(user.getId());
		}
		String reqString = DES3Util.decode(request.getQueryString());
		reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
		HashMap<String, Object> reqMap = CommonUtil.jsonObjToHashMap(reqString);
		String mobileNumber = paramsMap.get("mobileNumber")==null?String.valueOf(reqMap.get("mobileNumber")):""; // 手机号
		
		if (StringUtil.isNotEmpty(mobileNumber)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mobile", mobileNumber);
			User user = userService.getUserByParm(map);
			return Long.valueOf(user.getId());
		}
		return null;
	}
}
